package asia.lics.system.service.impl;

import asia.lics.common.exception.ServiceException;
import asia.lics.common.utils.DateUtils;
import asia.lics.common.utils.SecurityUtils;
import asia.lics.system.domain.CTestPaper;
import asia.lics.system.domain.CTestPaperInfo;
import asia.lics.system.domain.vo.TestPaperImport;
import asia.lics.system.mapper.CTestPaperInfoMapper;
import asia.lics.system.mapper.CTestPaperMapper;
import asia.lics.system.mapper.FSubjectMapper;
import asia.lics.system.service.ICTestPaperService;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


/**
 * 试卷名称Service业务层处理
 *
 * @author ss-tutor
 * @date 2024-11-16
 */
@Service
public class CTestPaperServiceImpl implements ICTestPaperService {
    private static final Logger log = LoggerFactory.getLogger(CTestPaperServiceImpl.class);
    @Autowired
    private CTestPaperMapper cTestPaperMapper;
    @Autowired
    private CTestPaperInfoMapper cTestPaperInfoMapper;
    @Autowired
    private FSubjectMapper fSubjectMapper;

    /**
     * 查询试卷名称
     *
     * @param id 试卷名称主键
     * @return 试卷名称
     */
    @Override
    public CTestPaper selectCTestPaperById(Long id) {
        return cTestPaperMapper.selectCTestPaperById(id);
    }

    /**
     * 查询试卷名称列表
     *
     * @param cTestPaper 试卷名称
     * @return 试卷名称
     */
    @Override
    public List<CTestPaper> selectCTestPaperList(CTestPaper cTestPaper) {
        List<CTestPaper> cTestPapers = cTestPaperMapper.selectCTestPaperList(cTestPaper);
        for (CTestPaper testPaper : cTestPapers) {
            if (testPaper.getSubjectCode() != null) {
                testPaper.setSubjectName(fSubjectMapper.selectFSubjectById(Long.valueOf(testPaper.getSubjectCode())).getName());
            }
        }
        return cTestPapers;
    }

    /**
     * 新增试卷名称
     *
     * @param cTestPaper 试卷名称
     * @return 结果
     */
    @Override
    public int insertCTestPaper(CTestPaper cTestPaper) {
        cTestPaper.setCreateTime(DateUtils.getNowDate());
        return cTestPaperMapper.insertCTestPaper(cTestPaper);
    }

    /**
     * 修改试卷名称
     *
     * @param cTestPaper 试卷名称
     * @return 结果
     */
    @Override
    public int updateCTestPaper(CTestPaper cTestPaper) {
        cTestPaper.setUpdateTime(DateUtils.getNowDate());
        return cTestPaperMapper.updateCTestPaper(cTestPaper);
    }

    /**
     * 批量删除试卷名称
     *
     * @param ids 需要删除的试卷名称主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteCTestPaperByIds(Long[] ids) {
        int deleteCTestPaperByIds = cTestPaperMapper.deleteCTestPaperByIds(ids);
        cTestPaperInfoMapper.deleteCTestPaperInfoByPaperId(ids);
        return deleteCTestPaperByIds;
    }

    /**
     * 删除试卷名称信息
     *
     * @param id 试卷名称主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteCTestPaperById(Long id) {
        cTestPaperInfoMapper.deleteCTestPaperInfoByPaperId(new Long[]{id});
        return cTestPaperMapper.deleteCTestPaperById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(TestPaperImport testPaperImport) {
        if (Objects.equals(testPaperImport.getWebsiteName(), "0")) {
            qshx(testPaperImport);
        } else {
            log.error("未知网站");
            throw new ServiceException("未知网站");
        }
    }

    /**
     * 勤思好学
     */
    private void qshx(TestPaperImport testPaperImport) {
        HttpRequest request = HttpRequest.get(testPaperImport.getPath())
                .header("Token", testPaperImport.getToken());
        HttpResponse execute = request.execute();
        if (execute.getStatus() != 200) {
            log.error("请求失败");
            throw new ServiceException("请求失败");
        }
        String body = execute.body();
        JSONObject jsonObject = JSON.parseObject(body);
        Integer code = jsonObject.getInteger("code");
        if (code != 200) {
            log.error("请求失败，{}", jsonObject.getString("message"));
            throw new ServiceException("请求失败");
        }
        JSONObject data = jsonObject.getJSONObject("data");

        CTestPaper cTestPaper = new CTestPaper();
        cTestPaper.setName(data.getString("examName"));

//        删除重复名称的试卷
        deleteRepeatPaper(cTestPaper);

        cTestPaper.setCreateTime(DateUtils.getNowDate());
        cTestPaper.setCreateBy(SecurityUtils.getUsername());
        cTestPaperMapper.insertCTestPaper(cTestPaper);

        List<JSONObject> jsonObjects = data.getList("exerList", JSONObject.class);
        for (JSONObject object : jsonObjects) {
            CTestPaperInfo cTestPaperInfo = new CTestPaperInfo();
            cTestPaperInfo.setTitle(object.getString("title"));
            JSONArray rightKeyList = object.getJSONArray("rightKeyList");
            String join = String.join(",", rightKeyList.toList(String.class));
            cTestPaperInfo.setAnswer(join);

            cTestPaperInfo.setAnalysis(object.getString("analyze"));

            JSONObject options = new JSONObject();
            options.put("a", object.getString("a"));
            options.put("b", object.getString("b"));
            options.put("c", object.getString("c"));
            options.put("d", object.getString("d"));
            options.put("e", object.getString("e"));
            options.put("f", object.getString("f"));
            options.put("g", object.getString("g"));
            options.put("h", object.getString("h"));
            cTestPaperInfo.setOptions(options.toJSONString());

            cTestPaperInfo.setTestPaperId(cTestPaper.getId());
            cTestPaperInfo.setType(object.getString("answerType"));
            cTestPaperInfo.setSort((long) jsonObjects.indexOf(object) + 1);
            cTestPaperInfo.setScore(object.getBigDecimal("simExamScore"));
            cTestPaperInfoMapper.insertCTestPaperInfo(cTestPaperInfo);
        }
    }

    /**
     * 删除重复名称的试卷
     */
    private void deleteRepeatPaper(CTestPaper cTestPaper) {
        List<CTestPaper> cTestPapers = cTestPaperMapper.selectCTestPaperList(cTestPaper);
        for (CTestPaper testPaper : cTestPapers) {
            deleteCTestPaperById(testPaper.getId());
        }
    }
}
